import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Radio,
  Button,
  DatePicker,
  message,
  Divider, Icon, Tooltip,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import Check from './check';
import styles from '../UserManage.less';
import { channel } from '../../../common/options';
import moment from 'moment';
import { powerBtnFunc } from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

/* eslint react/no-multi-comp:0 */
@connect(({ creditModels, loading }) => ({
  creditModels,
  loading: loading.models.creditModels,
}))

@Form.create()
class DeptManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    visibleCheck: false,
    selectedRows: {},
    formValues: {},
    status: 1,
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };


  constructor(props) {
    super(props);

  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { status } = this.state;
    dispatch({
      type: 'creditModels/fetch',
      payload: {
        status: status,
      },
    });
  }

  onChange = (e) => {
    const { dispatch } = this.props;
    this.setState({
      status: e.target.value,
    });
    dispatch({
      type: 'creditModels/fetch',
      payload: {
        status: e.target.value,
      },
    });
  };


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { status } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      status: status,
    };


    dispatch({
      type: 'creditModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { status } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'creditModels/fetch',
      payload: {
        status: status,
      },
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      fieldsValue.endTime = fieldsValue.endTime ? moment(fieldsValue.endTime).format('YYYY-MM-DD') : '';
      fieldsValue.startTime = fieldsValue.startTime ? moment(fieldsValue.startTime).format('YYYY-MM-DD') : '';
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'creditModels/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: record,
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'creditModels/getDesc',
          payload: { code: record.creditNo },
        });
      }
    });
  };
  handleCheck = (flag, record) => {
    this.setState({
      visibleCheck: !!flag,
      selectedRows: record,
    });
  };

  passCheck = (flag, record) => {
    const { dispatch } = this.props;
    const { selectedRows, pagination } = this.state;
    let _this = this;
    dispatch({
      type: 'creditModels/audit',
      payload: { code: selectedRows.creditNo, ...record },
      callback(res) {
        if (res.code === 200) {
          _this.handleCheck(false, []);
          dispatch({
            type: 'creditModels/fetch',
            payload: {
              status: _this.state.status,
              ...pagination,
            },
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }

      },
    });
  };
  //重复授信
  handleAdd = fields => {
    const { dispatch } = this.props;
    const { pagination, status } = this.state;

    dispatch({
      type: 'creditModels/credit',
      payload: fields,
      callback: (res) => {
        if (res.code === 200) {
          this.handleModalVisible(false, []);
          dispatch({
            type: 'creditModels/fetch',
            payload: {
              status: status,
              ...pagination,
            },
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }
      },
    });

  };
  //修改请求
  handleUpdate = fields => {
    const { pagination, status } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'creditModels/update',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'creditModels/fetch',
          payload: { ...pagination, status: status },
        });
        this.handleUpdateModalVisible(false, []);
      },
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入企业名称"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="企业简称">
              {getFieldDecorator('shortName')(<Input placeholder="请输入企业简称"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="渠道">
              {getFieldDecorator('channelNo')(
                <Select placeholder="请选择资金渠道" style={{ width: '100%' }}>
                  {channel.map(item => (
                    <Option value={item.key} key={item.key} disabled={item.disabled}>{item.value}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

          <Col md={8} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('startTime')(
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="选择开始时间"
                />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="结束时间">
              {getFieldDecorator('endTime')(
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="选择结束时间"
                />,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }

  checkDom = (code,dom) => {
    console.log(111);
    console.log(powerBtnFunc(code, dom));
    if(powerBtnFunc(code,dom)){
      this.setState({
        status:1
      })
    }
    return powerBtnFunc(code,dom)
  };

  render() {
    const { creditModels: { data, setDesc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView, visibleCheck, status } = this.state;

    const statustype = (val) => {
      if (val.status === 1) {
        return '未审核';
      } else if (val.status === 2) {
        return '通过';
      } else if (val.status === 3) {
        return <Tooltip title={val.reason}>
          驳回<Icon type="info-circle-o" style={{ marginRight: 4 }}/>
        </Tooltip>;
      }
    };
    const dom1 = (record) => powerBtnFunc('100126',
      [<a key={'btn1'} disabled={record.status === 2} onClick={() => this.handleUpdateModalVisible(true, record)}>授信</a>,
        <Divider key={'divider1'} type="vertical"/>],
    );
    const dom2 = (record) => powerBtnFunc('100128',
      [<a
        key={'btn2'} onClick={() => this.handleModalVisible(true, record)}>重新授信</a>,
        <Divider key={'divider2'} type="vertical"/>],
    );
    const dom3 = (record) => powerBtnFunc('100127',
      [<a key={'btn3'} onClick={() => this.handleCheck(true, record)}>审核</a>,
        <Divider key={'divider3'} type="vertical"/>],
    );
    const dom4 = (record) => powerBtnFunc('100125',
      <a key={'btn4'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
    );
    const arr = status !== 1 ? [
      {
        title: '授信时间',
        dataIndex: 'lastAuditTime',
        key: 'lastAuditTime',
      },
    ] : '';
    const columns = [
      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
        key: 'enterpriseName',
      },

      {
        title: '企业简称',
        dataIndex: 'shortName',
        key: 'shortName',
      },
      {
        title: '授信额度(元)',
        dataIndex: 'amount',
        key: 'amount',
      },
      {
        title: '剩余额度(元)',
        dataIndex: 'surplusAmount',
        key: 'surplusAmount',
      },

      ...arr,
      {
        title: '到期时间',
        dataIndex: 'expireTime',
        key: 'expireTime',
      },
      {
        title: '授信渠道',
        dataIndex: 'channelNo',
        key: 'channelNo',
        render: val => <span>{channel.map((item) => {
          if (item.key === Number(val)) {
            return item.value;
          }
        })}</span>,
      },
      {
        title: '授信状态',
        key: 'status',
        render: val => <span key={val}>{statustype(val)}</span>,
      },
      {
        title: '操作',
        key: 'key',
        render: (text, record) => {
          return (
            <Fragment>
              {status === 1 ? [dom3(record), dom4(record)] : ''}
              {status === 2 ? [dom2(record), dom4(record)] : ''}
              {status === 3 ? [dom1(record), dom4(record)] : ''}
            </Fragment>
          );
        },
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper title="信审管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div style={{ marginBottom: '20px' }}>
              <RadioGroup defaultValue={status} onChange={this.onChange}>
                <RadioButton value={1}>待审核</RadioButton>
                <RadioButton value={2}>审核通过</RadioButton>
                <RadioButton value={3}>审核驳回</RadioButton>
              </RadioGroup>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowSelectHide={true}
              rowKey={'creditNo'}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {setDesc
          ?
          <DescView handleLookDesc={this.handleLookDesc} selectedRows={setDesc} lookDescView={lookDescView}/>
          :
          ''}
        <Check visibleCheck={visibleCheck} passCheck={this.passCheck} handleCheck={this.handleCheck}/>
        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
          data={data}
        />

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
